package com.cslc.mp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cslc.mp.constant.MpInfo;
import com.cslc.mp.dao.DAOFactory;
import com.cslc.mp.dao.vo.Fault;
import com.cslc.mp.service.CoreServiceFactory;
import com.cslc.mp.util.JsSignUtil;
import com.cslc.mp.util.SignUtil;
import com.cslc.mp.util.WeChatUtil;

public class FaultReportServlet extends HttpServlet {

	Logger logger = Logger.getLogger(FaultReportServlet.class.getName());
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//TODO 进行签名验签，时间戳判断
		// 微信加密签名 
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 微信用户id
        String openId = request.getParameter("OpenId");
        PrintWriter out = response.getWriter();  
        if(signature == null || signature.length() <= 0)
        	logger.error("signature为空！");
        else {
        	logger.debug("开始校验用户signature :" + signature);
          	//如果校验成功
        	if(signature.equals(SignUtil.createSignature(openId, MpInfo.TOKEN, timestamp))) {
            	logger.debug("signature校验成功");
            	//如果链接未超时
            	if(System.currentTimeMillis() - Long.parseLong(timestamp) < MpInfo.TIME_OUT) {
            		logger.debug("timestamp校验成功,未超时");
            		
            		//构造wx.config
            		String jsApiTicket = WeChatUtil.getJsApiTicket().getTicket();
            		String faultReportUrl = MpInfo.HOST + "/fault_report.jsp";
            		Map<String, String> signPackage = JsSignUtil.sign(jsApiTicket, faultReportUrl);
            		
            		HttpSession session = request.getSession();
            		session.setAttribute("openid", openId);
            		session.setAttribute("timestamp", signPackage.get("timestamp"));
            		session.setAttribute("nonceStr", signPackage.get("nonceStr"));
            		session.setAttribute("signature", signPackage.get("signature"));
            	
            		logger.debug("该用户的session id是：" + session.getId());
            		try {
            			
                	   	response.sendRedirect(MpInfo.HOST + "/fault_report.jsp");
    				} catch (Exception e) {
    					logger.error(e.getMessage());
    					response.getWriter().print(e);
    				}
            	}
            	else {
            		response.sendRedirect(MpInfo.HOST + "/bind_timeout.jsp");
            		logger.info("该链接已超时");
            	}
         
            }
            else {
            	logger.error("signature校验失败");
            }
        }    
        out.close();
        out = null; 
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String serverId = request.getParameter("serverId");
		String openId = (String) request.getSession().getAttribute("openid");
		String[] mediaIdStr = serverId.split(",");
		for(int i=0; i<mediaIdStr.length; i++) {
			CoreServiceFactory.getInstance().tempMaterialGet(mediaIdStr[i]);
		}
		
        String content = request.getParameter("content");
        logger.debug("serverId: " + serverId + "\n" + "content: " + content);
        
        //对象赋值
        Fault fault = new Fault();
        fault.setOpenid(openId);
        fault.setContent(content);
        fault.setPicId(serverId);
        //获取当前时间戳
        Integer timestamp = (int) (System.currentTimeMillis()/1000);
        fault.setCreateTime(timestamp);
        
        try {
			if(DAOFactory.getIFaultDAOInstance().doCreate(fault)) {
				logger.info("故障提交成功！");
			}
			else{
				logger.error("故障提交失败！");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}
}
